package b1.mobile.blackberry.screen;

import net.rim.device.api.i18n.ResourceBundle;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.DeviceInfo;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.DrawStyle;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.FontFamily;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.XYEdges;
import net.rim.device.api.ui.component.BasicEditField;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.PasswordEditField;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.container.GridFieldManager;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.util.StringProvider;
import b1.mobile.blackberry.controller.AgentController;
import b1.mobile.blackberry.io.http.Serviceworker;
import b1.mobile.blackberry.io.http.Serviceworker.ServiceDelegate;
import b1.mobile.blackberry.io.http.SoapContentProvider;
import b1.mobile.blackberry.res.B1resourceResource;
import b1.mobile.blackberry.ui.component.EditField;
import b1.mobile.blackberry.ui.component.util.FontFactory;
import b1.mobile.blackberry.ui.component.util.ProgressAnimationField;

/**
 * 
 * @author YangShen
 * 
 */
public class WelcomeScreen extends MainScreen implements B1resourceResource, ServiceDelegate{

	private static ResourceBundle resources = ResourceBundle.getBundle(
			BUNDLE_ID, BUNDLE_NAME);

	private BasicEditField username;
	private PasswordEditField password;

	private HorizontalFieldManager buttonFieldManager;
	private ButtonField login;
	private ButtonField cancel;

	private Manager footFieldManager;
	Font labelFont;
	
	private HorizontalFieldManager serverFieldManager;
	
	LabelField status;

	public boolean timeOut = false;
	
	public WelcomeScreen() {
		Font titleFont = getFont();
		labelFont = getFont();
		try{
			FontFamily ff = FontFamily.forName("Alpha Sans");
			titleFont = ff.getFont(Font.BOLD, 27, Ui.UNITS_px);
			labelFont = ff.getFont(Font.PLAIN, 6, Ui.UNITS_pt);
		} catch (Exception ex){
			
		}
		
		XYEdges titleEdges = new XYEdges(25,30,10,30);
		XYEdges fieldEdges = new XYEdges(10,30,0,50);
		
		//setTitle(resources.getString(TITLE));
		this.setTitle(new Field(Field.USE_ALL_WIDTH) {			
			protected void layout(int width, int height) {
				setExtent(width, getPreferredHeight());
			}
			
			public int getPreferredHeight() {
				return 16;
			}

			protected void paint(Graphics graphics) {
				graphics.setColor(0x00F8BC00);
				graphics.fillRect(0, 0, getExtent().width, getPreferredHeight());
			}
			
		});
		
		footFieldManager = new VerticalFieldManager();			
		Manager copyRightMgr = new HorizontalFieldManager(Field.FIELD_BOTTOM){
			protected void subpaint(Graphics graphics) {
				graphics.setColor(0x00808080);
				super.subpaint(graphics);
			};
		};
		copyRightMgr.add(new BitmapField(Bitmap.getBitmapResource("_SAP_FOOT_LOGO.png")));
		LabelField copyRights = new LabelField("2011 SAP. All rights reserved.", Field.FIELD_RIGHT);
		copyRights.setFont(labelFont);
		copyRights.setPadding(14, 0, 0, 10);
		copyRightMgr.add(copyRights);

		footFieldManager.setPadding(0, 30, 24, 30);
		footFieldManager.add(copyRightMgr);
		this.setStatus(footFieldManager);
		
		status = new LabelField(resources.getString(LABEL_SERVER_STATUS_CONNECT));
		status.setFont(labelFont);
		
		
		VerticalFieldManager logoFieldManager = new VerticalFieldManager(USE_ALL_WIDTH);		
		RichTextField mainTitle = new RichTextField("BUSINESS ONE MOBILE", Field.NON_FOCUSABLE);
		
		mainTitle.setFont(titleFont);
		mainTitle.setMargin(titleEdges);
		logoFieldManager.add(mainTitle);
//		logoFieldManager.add(new LabelField(resources.getString(LABEL_WELCOME_SUB_TITLE)));
		
		this.add(logoFieldManager);
		
		Manager userMgr = new HorizontalFieldManager(Field.FIELD_HCENTER){
			public int getPreferredWidth() {return Display.getWidth() * 9 / 10;}
		};
		userMgr.setPadding(16, 0, 0, 0);
		LabelField lblUser = new LabelField("Login:", DrawStyle.RIGHT | Field.FIELD_HCENTER){
			public int getPreferredWidth(){return Display.getWidth() * 3 / 10;}
		};
		lblUser.setPadding(8, 10, 0, 0);
		lblUser.setFont(labelFont.derive(Font.BOLD));
		
		username = new BasicEditField("", "", 20, FIELD_HCENTER){
			public int getPreferredWidth(){return Display.getWidth() * 6 / 10;}
			protected void paintBackground(Graphics g) {
				g.setColor(0x00CCCCCC);
				g.drawRoundRect(0, 0, getPreferredWidth(), getExtent().height, 12, 12);
				super.paintBackground(g);
			}
		};
//		username.setMargin(fieldEdges);
		username.setFont(labelFont);
		username.setPadding(8, 8, 8, 8);
		
		userMgr.add(lblUser);
		userMgr.add(username);
		
		
		Manager pwdMgr = new HorizontalFieldManager(Field.FIELD_HCENTER){
			public int getPreferredWidth() {return Display.getWidth() * 9 / 10;}
		};
		pwdMgr.setPadding(16, 0, 0, 0);
		LabelField lblPwd = new LabelField("Password:", DrawStyle.RIGHT | Field.FIELD_HCENTER){
			public int getPreferredWidth(){return Display.getWidth() * 3 / 10;}
		};
		lblPwd.setPadding(8, 10, 0, 0);
		lblPwd.setFont(labelFont.derive(Font.BOLD));
		
		password = new PasswordEditField("", "", 20, FIELD_HCENTER){
			public int getPreferredWidth(){return Display.getWidth() * 6 / 10;}
			protected void paintBackground(Graphics g) {
				g.setColor(0x00CCCCCC);
				g.drawRoundRect(0, 0, getPreferredWidth(), getExtent().height, 12, 12);
				super.paintBackground(g);
			}
		};
		password.setPadding(8, 8, 8, 8);
		password.setFont(labelFont);
		
		pwdMgr.add(lblPwd);
		pwdMgr.add(password);
	
		VerticalFieldManager loginFieldManager = new VerticalFieldManager(Field.FIELD_HCENTER | USE_ALL_WIDTH);
		loginFieldManager.add(userMgr);
		loginFieldManager.add(pwdMgr);

		buttonFieldManager = new HorizontalFieldManager(FIELD_HCENTER);
		login = new ButtonField(resources.getString(BUTTON_LOGIN),
				ButtonField.CONSUME_CLICK | ButtonField.NEVER_DIRTY
						| FIELD_HCENTER){
			public int getPreferredWidth() {
				return Display.getWidth() * 8 / 10;
			};
		};
		cancel = new ButtonField(resources.getString(BUTTON_CANCEL),
				ButtonField.CONSUME_CLICK | ButtonField.NEVER_DIRTY
						| FIELD_HCENTER);
		login.setFont(labelFont);
		cancel.setFont(labelFont);
		
		buttonFieldManager.add(login);
//		buttonFieldManager.add(cancel);
		buttonFieldManager.setMargin(16, 0, 0, 0);
		
		loginFieldManager.add(buttonFieldManager);
		this.add(loginFieldManager);
		
		MenuItem settings = new MenuItem(new StringProvider("Settings"), 0x0230010, 0){
			public void run(){
				UiApplication.getUiApplication().pushScreen(new SettingsScreen());
			}
		};
		
		addMenuItem(settings);
	}

	protected void onUiEngineAttached(boolean attached) {
		if (attached) {
			login.setChangeListener(new FieldChangeListener() {
				public void fieldChanged(Field field, int context) {
					onLogin();
				}
			});
			
			cancel.setChangeListener(new FieldChangeListener() {
				public void fieldChanged(Field field, int context) {
					onCancel();
				}
			});
		}
	}
	
	protected void onFocusNotify(boolean focus) {
		super.onFocusNotify(focus);
		
		if(focus){
			String userName = AgentController.Configuration.getUserCode();
			if(userName.trim().length() > 0){
				username.setText(userName);
				password.setText("");
				password.setFocus();
			} else {
				setFocus();
			}
		}
	}

	protected void onCancel() {
		System.exit(0);
	}

	protected void onLogin() {
		
		// TODO: Login Logic comment out temporally
		onLoading();
		String userName = username.getText();
		String passWord = password.getText();
		String phoneNum = AgentController.Configuration.getPhoneNum();
		String company = AgentController.Configuration.getCompanyDB();
		String deviceID = Integer.toHexString(DeviceInfo.getDeviceId());
		
		String[] names = new String[]{"userName", "password", "phoneNum", "deviceIMEI", "companyDB"};
		String[] values = new String[]{userName, passWord, phoneNum, deviceID, company};
		SoapContentProvider soap = new SoapContentProvider("Connect", names, values);
		
		try{
			Serviceworker.session_id = null;
			Serviceworker connWorker = new Serviceworker(this, AgentController.getServer(), soap);
			new Thread(connWorker).start();//UiApplication.getUiApplication().invokeLater(connWorker);
			
		} catch (Exception ex){
			onLoadingDone();
			status.setText(ex.getMessage());
			onLoading();
		}
		
//		getUiEngine().pushScreen(new BPListScreen());
	}

	public void onGetResult(Serviceworker worker) {
		if(worker.responseCode == 200){
			UiApplication.getUiApplication().invokeLater(new Runnable(){
				public void run() {
					getUiEngine().pushScreen(new HomeScreen());
					onLoadingDone();
				}
			});			
		}
	}
	
	private void onLoading(){
		ProgressAnimationField loadingIcon = new ProgressAnimationField(Bitmap.getBitmapResource("spinner.png"), 5, Field.FIELD_HCENTER );
		serverFieldManager = new HorizontalFieldManager();
		serverFieldManager.add(status);
		serverFieldManager.add(loadingIcon);
		footFieldManager.insert(serverFieldManager, 0);
	}
	
	private void onLoadingDone(){
		serverFieldManager.delete(status);
		footFieldManager.delete(serverFieldManager);
	}
	
	public boolean isDirty() {
		return false;
	}
}
